package com.learn.mybtsp.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.learn.mybtsp.mapper.UserMapper;
import com.learn.mybtsp.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public List<User> findAll(){
        String userListJsonStr = redisTemplate.opsForValue().get("UserService.findAll");
        if(StringUtils.isNotBlank(userListJsonStr)){
            List<User> users = JSON.parseArray(userListJsonStr, User.class);
            log.info("redis cache.......");
            return users;
        }else{
            List<User> users = userMapper.selectList(new LambdaQueryWrapper<>());
            redisTemplate.opsForValue().set("UserService.findAll", JSON.toJSONString(users), 2, TimeUnit.HOURS);
            log.info("add redis cache++++++");
            return users;
        }

    }

    public List<User> findPage(int page,int size){
        Page<User> objectPage = new Page<>(page, size);
        Page<User> userPage = userMapper.selectPage(objectPage, new LambdaQueryWrapper<>());
        log.info("total", userPage.getTotal());
        log.info("pages", userPage.getPages());
        return userPage.getRecords();
    }

    public List<User> findAge(int age){
        // List<User> userGtAge = userMapper.findUserGtAge(age);
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 使用LambdaQueryWrapper进行查询，不用编写自定义的sql
        userLambdaQueryWrapper.gt(User::getAge, age);
        return userMapper.selectList(userLambdaQueryWrapper);
    }

    public Long save(String name) {
        User user = new User();
        user.setAge(12);
        user.setEmail("ccc@qq.com");
        user.setName(name);
        userMapper.insert(user);
        return user.getId();
    }

//    生成着
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public void send(){
//        发送消息
        User user = this.userMapper.selectById(1L);
        rocketMQTemplate.convertAndSend("topic_springboot", user);
    }
}
